/*   
 * Copyright (c) 2010-2020 DMGIS Ltd. All Rights Reserved.   
 *   
 * This software is the confidential and proprietary information of   
 * DMGIS. You shall not disclose such Confidential Information   
 * and shall use it only in accordance with the terms of the agreements   
 * you entered into with DMGIS.   
 *   
 */
package com.dmgis.qxfw.controller;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.dmgis.qxfw.service.IMongoService;
import com.dmgis.qxfw.utils.AchieveRandom;
import com.google.common.collect.Maps;

import static java.util.Map.*;


@Controller
@RequestMapping("/dataservice")
public class DataServiceController {

	@Resource
	IMongoService mongoService;

	@RequestMapping("/select")
	@ResponseBody
	public Object selectData(HttpServletRequest request, Model model, HttpServletResponse response) throws UnsupportedEncodingException {
		System.out.println("-------------------------------------------------------------------------");
		byte[] result = null;
		String collectionName = "";
		Enumeration<String> em = request.getParameterNames();
		Map<String, Object> queryMap = Maps.newHashMap();
		while (em.hasMoreElements()) {
			String name = (String) em.nextElement();
			String value = request.getParameter(name);
			if ("collectionName".equals(name)) {
				collectionName = value;
			} else {
				queryMap.put(name, value);
			}
		}
		if (StringUtils.isBlank(collectionName)) {
			return "collectionName参数不能为空，请确定数据库表名称";
		}
		try {
			result = mongoService.selectData(collectionName, queryMap);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		// dataArrayList.add(new
		// String(result,"ISO-8859-1"));//注意，这里要先将二进制转变成string对象，这样在处理返回结果的时候将string转变成byte才不会出错
		//String string = new String(result,"ISO-8859-1");
		return result;
	}
	
	@RequestMapping("/download")
	@ResponseBody
	public Object download(HttpServletRequest request, Model model,HttpServletResponse response) throws UnsupportedEncodingException {
		System.out.println("-------------------------------------------------------------------------");
		byte[] result = null;
		String collectionName = "";
		Enumeration<String> em = request.getParameterNames();
		Map<String, Object> queryMap = Maps.newHashMap();
		while (em.hasMoreElements()) {
			String name = (String) em.nextElement();
			String value = request.getParameter(name);
			if ("collectionName".equals(name)) {
				collectionName = value;
			} else {
				queryMap.put(name, value);
			}
		}
		if (StringUtils.isBlank(collectionName)) {
			return "collectionName参数不能为空，请确定数据库表名称";
		}
		try {
			result = mongoService.selectData(collectionName, queryMap);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		AchieveRandom rand = new AchieveRandom();
		String fileName = "";
		if(collectionName!=null&&collectionName.length()>0){
			fileName = rand.getFileName(collectionName);
		}
		response.setContentType("application/octet-stream;charset=ISO8859-1");
		BufferedOutputStream output = null;
		try {
			output = new BufferedOutputStream(response.getOutputStream());
			String fileNameDown = new String(fileName.getBytes(), "ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileNameDown);
			output.write(result);
			response.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping("/exist")
	@ResponseBody
	public Object exists(HttpServletRequest request, Model model) throws UnsupportedEncodingException {
		System.out.println("-------------------------------------------------------------------------");
		long result = 0;
		String collectionName = "";
		Enumeration<String> em = request.getParameterNames();
		Map<String, Object> queryMap = Maps.newHashMap();
		while (em.hasMoreElements()) {
			String name = (String) em.nextElement();
			String value = request.getParameter(name);
			if ("collectionName".equals(name)) {
				collectionName = value;
			} else {
				queryMap.put(name, value);
			}
		}
		if (StringUtils.isBlank(collectionName)) {
			return "collectionName参数不能为空，请确定数据库表名称";
		}
		try {
			result = mongoService.existData(collectionName, queryMap);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		// dataArrayList.add(new
		// String(result,"ISO-8859-1"));//注意，这里要先将二进制转变成string对象，这样在处理返回结果的时候将string转变成byte才不会出错
		return result;
	}

	@RequestMapping("/insert")
	@ResponseBody
	public Object insertData(HttpServletRequest request, Model model) {
		System.out.println("-------------------------------------------------------------------------");
		int result = 0;
		int count = 0;
		String collectionName = "";
		Enumeration<String> em = request.getParameterNames();
		Map<String, Object> insertMap = Maps.newHashMap();
		while (em.hasMoreElements()) {
			String name = (String) em.nextElement();
			String value = request.getParameter(name);
			if ("collectionName".equals(name)) {
				collectionName = value;
			} else {
				insertMap.put(name, value);
			}
		}
		if (StringUtils.isBlank(collectionName)) {
			return "collectionName参数不能为空，请确定数据库表名称";
		}
		// List<MultipartFile> files = new ArrayList<MultipartFile>();
		try {
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			if (request instanceof MultipartHttpServletRequest) {
				// 将request变成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				Iterator<String> iter = multiRequest.getFileNames();
				// 检查form中是否有enctype="multipart/form-data"
				if (multipartResolver.isMultipart(request) && iter.hasNext()) {
					// 获取multiRequest 中所有的文件名
					while (iter.hasNext()) {
						// 一次遍历所有文件
						MultipartFile file = multiRequest.getFile(iter.next().toString());
						if (file != null) {
							// insertMap.put("fileName", file.getName());
							insertMap.put("data", file.getBytes());
							int flag = mongoService.insertData(collectionName, insertMap);
							result += flag;
							count++;
							// files.add(file);
						}
						// 适配名字重复的文件
						// List<MultipartFile> fileRows =
						// multiRequest.getFiles(iter.next().toString());
						// if (fileRows != null && fileRows.size() != 0) {
						// for (MultipartFile file : fileRows) {
						// if (file != null && !file.isEmpty()) {
						// insertMap.put("fileName", file.getName());
						// insertMap.put("data", file.getBytes());
						// mongoService.insertData(insertMap);
						// files.add(file);
						// }
						// }
						// }
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return String.format("总共插入了%d个文件，成功了%d个文件", result, count);
	}

//	@PostMapping("/insert")
//	public String insertData(@RequestParam("collectionName") String collectionName,
//						 @RequestParam("data") MultipartFile file) {
//	if (collectionName == null || collectionName.trim().isEmpty()) {
//		return "collectionName参数不能为空，请确定数据库表名称";
//	}
//
//	try {
//		// 检查文件是否为空
//		if (file.isEmpty()) {
//			return "文件不能为空";
//		}
//
//		// 将文件数据写入数据库（假设您有一个名为mongoService的服务，提供insertData方法）
//		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//		IOUtils.copy(file.getInputStream(), outputStream); // 使用Apache Commons IO库将文件流复制到ByteArrayOutputStream
//		byte[] bytes = outputStream.toByteArray();          // 转换为字节数组
//
//		Map<String, Object> insertMap = new HashMap<>();
//		insertMap.put("data", bytes);
//
//		int flag = mongoService.insertData(collectionName, insertMap);
//		return String.format("总共插入了1个文件，成功了%d个文件", flag);
//	} catch (IOException e) {
//		return "文件读取错误: " + e.getMessage();
//	} catch (Exception e) {
//		return "文件插入失败: " + e.toString();
//	}
//	}





	@RequestMapping("/update")
	@ResponseBody
	public Object updateData(HttpServletRequest request, Model model) {
		System.out.println("-------------------------------------------------------------------------");
		long count = 0;
		Enumeration<String> em = request.getParameterNames();
		String collectionName = "";
		Map<String, Object> updateMap = Maps.newHashMap();
		Map<String, Object> updateData = Maps.newHashMap();
		while (em.hasMoreElements()) {
			String name = (String) em.nextElement();
			String value = request.getParameter(name);
			if ("collectionName".equals(name)) {
				collectionName = value;
			} else {
				updateMap.put(name, value);
			}
		}
		if (StringUtils.isBlank(collectionName)) {
			return "collectionName参数不能为空，请确定数据库表名称";
		}
		// List<MultipartFile> files = new ArrayList<MultipartFile>();
		try {
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			if (request instanceof MultipartHttpServletRequest) {
				// 将request变成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				Iterator<String> iter = multiRequest.getFileNames();
				// 检查form中是否有enctype="multipart/form-data"
				if (multipartResolver.isMultipart(request) && iter.hasNext()) {
					// 获取multiRequest 中所有的文件名
					while (iter.hasNext()) {
						// 一次遍历所有文件
						MultipartFile file = multiRequest.getFile(iter.next().toString());
						if (file != null) {
							// insertMap.put("fileName", file.getName());
							updateData.put("data", file.getBytes());
							count = mongoService.updateData(collectionName, updateMap, updateData);
							// files.add(file);
						}
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		String result = "";
		if (count == -1) {
			result = "更新失败";
		} else {
			result = String.format("成功更新了%d个文件", count);
		}
		return result;
	}

	@RequestMapping("/delete")
	@ResponseBody
	public Object deleteData(HttpServletRequest request, Model model) {
		System.out.println("-------------------------------------------------------------------------");
		long count = 0;
		Enumeration<String> em = request.getParameterNames();
		Map<String, Object> deleteMap = Maps.newHashMap();
		String collectionName = "";
		while (em.hasMoreElements()) {
			String name = (String) em.nextElement();
			String value = request.getParameter(name);
			if ("collectionName".equals(name)) {
				collectionName = value;
			} else {
				deleteMap.put(name, value);
			}
		}
		if (StringUtils.isBlank(collectionName)) {
			return "collectionName参数不能为空，请确定数据库表名称";
		}
		try {
			count = mongoService.deleteData(collectionName, deleteMap);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		String result = "";
		if (count == -1) {
			result = "删除失败";
		} else {
			result = String.format("成功删除了%d个文件", count);
		}
		return result;
	}
}
